package com.budwk.app.sqfw.controllers.admin.customservice;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.services.common.SqfwCommonForAdminService;
import com.budwk.app.sqfw.services.common.SqfwCustomForAdminCommonService;
import com.budwk.app.sqfw.vo.SqfwCustomForAdminCommonVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwV2.constants.ProblemConstant;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskParamDataDTO;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskPdfDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.ProblemParamDTO;
import com.budwk.app.sqfwV2.enums.BinYangFileServiceEnum;
import com.budwk.app.sqfwV2.enums.CenturyCitySafeServiceEnum;
import com.budwk.app.sqfwV2.enums.HiddenDangerEnum;
import com.budwk.app.sqfwV2.enums.centuryCitySafe.CampusTrainingProblemsEnum;
import com.budwk.app.sqfwV2.enums.centuryCitySafe.EnterpriseSafetyProblemsEnum;
import com.budwk.app.sqfwV2.enums.centuryCitySafe.LargeSafeProblemsEnum;
import com.budwk.app.sqfwV2.service.ProblemInfoService;
import com.budwk.starter.common.openapi.annotation.*;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.log.annotation.SLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;

import java.util.List;

/**
 * @program: dfxy-community
 * @description: 世纪城安全巡查（后台管理系统）
 * @author: LJT
 * @create: 2024-02-18 16:21
 **/
@IocBean
@At("/platform/sqfw/CenturyCitySec")
@ApiDefinition(tag = "世纪城安全巡查（后台管理系统）")
@Slf4j
public class CenturyCitySecurityForAdminController {

    @Inject(value = "CenturyCitySecurityForAdminService")
    private SqfwCustomForAdminCommonService sqfwCustomForAdminCommonService;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private SqfwCommonForAdminService sqfwCommonForAdminService;


    @Inject
    private ProblemInfoService problemInfoService;

    /**
     * 列表查询
     */
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "列表查询")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "create_date", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = SqfwCustomForAdminCommonVO.class
    )
    @ApiResponses(
            implementation = SqfwCustomForAdminCommonVO.class
    )
    @SLog(tag = "公共列表查询（后台管理系统）", value = "${args[0]}}")
    @SaCheckLogin
    public Result<?> list(@Param("..") SqfwCustomForAdminCommonVO bean) {
        Pagination pagination = sqfwCustomForAdminCommonService.list(bean);
        return Result.data(pagination);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @At
    @Ok("json")
    @DELETE
    @ApiOperation(name = "删除列表信息")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SLog(tag = "删除消防信息", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> delete(@Param("id") String id) {
        sqfwCustomForAdminCommonService.delete(id);
        return Result.success();
    }

    @At("/batchDelete")
    @Ok("json")
    @DELETE
    @ApiOperation(name = "批量删除表数据")
    @SLog(tag = "批量删除表数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> batchDelete(@Param("ids") List<String> ids) {
        return Result.data(sqfwCommonForAdminService.batchDelete(ids));
    }

    /**
     * 获取下载文件列表及数据检查
     */
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "获取下载文件列表及数据检查")
    @ApiResponses(
            implementation = SqfwCustomForAdminCommonVO.class
    )
    @SLog(tag = "获取下载文件列表及数据检查", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> checkDataInfoList(@Param("..") SqfwCustomForAdminCommonVO sqfwFormSummaryForAdminVO) {
        return Result.data(sqfwCustomForAdminCommonService.checkDataInfoList(sqfwFormSummaryForAdminVO));
    }

    /**
     * excel下载
     *
     * @param sqfwFormSummaryForAdminVO
     * @return
     */
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "Excel文件下载")
    @SLog(tag = "Excel文件下载", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> downloadExcel(@Param("excelConfigList") List<ExcelCreateConfig> excelConfigList, @Param("..") SqfwCustomForAdminCommonVO sqfwFormSummaryForAdminVO) {
        return Result.data(sqfwCustomForAdminCommonService.downloadExcel(excelConfigList, sqfwFormSummaryForAdminVO));
    }

    /**
     * pdf下载
     *
     * @param sqfwFormSummaryForAdminVO
     * @return
     */
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "pdf文件下载")
    @SLog(tag = "pdf文件下载", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> downloadPdf(@Param("excelConfigList") List<ExcelCreateConfig> excelConfigList, @Param("..") SqfwCustomForAdminCommonVO sqfwFormSummaryForAdminVO) {
        return Result.data(sqfwCustomForAdminCommonService.downloadPdf(excelConfigList, sqfwFormSummaryForAdminVO));
    }

    /**
     * 重置(重新生成pdf)
     */
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "重新生成pdf")
    @ApiResponses(
            implementation = String.class
    )
    @SLog(tag = "重新生成pdf", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> reGeneratePdf(@Param("flowId") String flowId) {
        sqfwCustomForAdminCommonService.reGeneratePdf(flowId);
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "获取详情")
    @ApiResponses
    @SLog(tag = "获取详情", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> getHiddenDangerInfo(@Param("hiddenDangerList") List<SqfwCustomForAdminCommonVO> bean, @Param("id") String id) {
        return Result.data(getHiddenInfo(bean, id).getData());
    }

    public Result<?> getHiddenInfo(List<SqfwCustomForAdminCommonVO> bean, String id) {
        if (bean.size() <= 0) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        StringBuffer sb = new StringBuffer();
        if (StringUtils.isNotEmpty(id)) {
            Sqfw_formSummary_new sqfwFormSummaryNew = sqfwFormsummaryNewService.fetch(id);
            if (ObjectUtil.isNotEmpty(sqfwFormSummaryNew)) {
                SafeCheckTaskPdfDTO safeCheckTaskPdfDTO = JSONObject.parseObject(sqfwFormSummaryNew.getParamData(), SafeCheckTaskPdfDTO.class);
                List<SafeCheckTaskParamDataDTO> safeCheckTaskParamDataDTOS = safeCheckTaskPdfDTO.getOtherHiddenDangers();
                if (ObjectUtils.isNotEmpty(safeCheckTaskParamDataDTOS)) {
                    safeCheckTaskParamDataDTOS.forEach(item -> {
                        if (StrUtil.isNotBlank(item.getRectificationType())) {
                            if (StringUtils.isNotEmpty(item.getRiskDesc())) {
                                sb.append(item.getRiskDesc()).append("\n");
                            }
                        }
                    });
                }
                if (safeCheckTaskPdfDTO.getType().equals(BinYangFileServiceEnum.ONE_EXCEL.getLabel())) {
                    List<SafeCheckTaskParamDataDTO> extraProblems = safeCheckTaskPdfDTO.getExtraProblemVo().getExistProblems();
                    extraProblems.forEach(item -> {
                        for (LargeSafeProblemsEnum largeSafeProblemsEnum : LargeSafeProblemsEnum.values()) {
                            if (!item.getKey().equals(LargeSafeProblemsEnum.getEnumByFields(item.getFields()).getDefaultValue())
                                    && !"enterpriseLaborDispatch".equals(item.getFields())) {
                                sb.append(item.getNineSmallPlacesIssuesAndRisks()).append("\n");
                                break;
                            }
                        }
                    });
                    return Result.data(sb.toString());
                } else if (safeCheckTaskPdfDTO.getType().equals(BinYangFileServiceEnum.TWO_EXCEL.getLabel())) {
                    List<SafeCheckTaskParamDataDTO> extraProblems = safeCheckTaskPdfDTO.getExtraProblemVo().getExistProblems();
                    extraProblems.forEach(item -> {
                        for (EnterpriseSafetyProblemsEnum largeSafeProblemsEnum : EnterpriseSafetyProblemsEnum.values()) {
                            if (!item.getKey().equals(EnterpriseSafetyProblemsEnum.getEnumByFields(item.getFields()).getDefaultValue())) {
                                sb.append(item.getNineSmallPlacesIssuesAndRisks()).append("\n");
                                break;
                            }
                        }
                    });
                    return Result.data(sb.toString());
                } else if (safeCheckTaskPdfDTO.getType().equals(BinYangFileServiceEnum.THREE_EXCEL.getLabel())) {
                    List<SafeCheckTaskParamDataDTO> extraProblems = safeCheckTaskPdfDTO.getExtraProblemVo().getExistProblems();
                    extraProblems.forEach(item -> {
                        for (CampusTrainingProblemsEnum campusTrainingProblemsEnum : CampusTrainingProblemsEnum.values()) {
                            if (!item.getKey().equals(CampusTrainingProblemsEnum.getEnumByFields(item.getFields()).getDefaultValue())) {
                                sb.append(item.getNineSmallPlacesIssuesAndRisks()).append("\n");
                                break;
                            }
                        }
                    });
                    return Result.data(sb.toString());
                } else if (safeCheckTaskPdfDTO.getType().equals(BinYangFileServiceEnum.FORE_EXCEL.getLabel())) {
                    List<SafeCheckTaskParamDataDTO> extraProblems = safeCheckTaskPdfDTO.getExtraProblemVo().getExistProblems();
                    List<ProblemParamDTO> problemParamDTOS = problemInfoService.getAllDefault(ProblemConstant.BINGYANG_LOGISTICS_PROBLEM_CODE);
                    extraProblems.forEach(item -> {
                        for (ProblemParamDTO problemParamDTO : problemParamDTOS) {
                            if (!problemParamDTO.getKey().equals(item.getKey())) {
                                sb.append(item.getNineSmallPlacesIssuesAndRisks()).append("\n");
                                break;
                            }
                        }
                    });
                    return Result.data(sb.toString());
                } else {
                    List<SafeCheckTaskParamDataDTO> safeCheckTaskParamDataDTOList = safeCheckTaskPdfDTO.getHiddenDanger();
                    safeCheckTaskParamDataDTOList.forEach(item -> {
                        if (HiddenDangerEnum.foodOtherInformation.getCode().equals(item.getRiskCode())) {
                            if (StringUtils.isNotEmpty(item.getFoodOtherInformation())) {
                                sb.append(item.getFoodOtherInformation()).append("\n");
                            }
                        }
                    });
                }
            }
        }
        for (SqfwCustomForAdminCommonVO s : bean) {
            String type = CenturyCitySafeServiceEnum.getCodeByType(s.getType());
            if (StringUtils.isNotEmpty(type)) {
                HiddenDangerEnum hiddenDangerEnum = HiddenDangerEnum.getHiddenDangerEnum(s.getCode(), type);
                if (ObjectUtil.isNotEmpty(hiddenDangerEnum)) {
                    if (hiddenDangerEnum.getFlag().equals(s.getFlag())) {
                        sb.append(hiddenDangerEnum.getResult()).append("\n");
                    }
                }
            }
        }
        return Result.data(sb.toString());
    }
}
